package com.linkage.educloud.ah.adapter.pic;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.linkage.educloud.ah.R;
import com.linkage.educloud.ah.bean.PicItem;
import com.linkage.educloud.ah.util.ImageLoader;
import com.zzhou.common.library.util.ToastShow;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;

/**
 * Created by Mr'Tang on 2018/9/19.
 */

public class BigpicAdapter extends PagerAdapter {
    private ArrayList<PicItem> mImages;
    private Context mcontext;
    private Bitmap bmp;
    private PopupWindow popWindow;

    public BigpicAdapter(Context context, ArrayList<PicItem> Images) {
        this.mImages = Images;
        this.mcontext = context;

    }

    //PagerAdapter只会缓存前三张图片，超出这个范围会调用它
    @Override
    public void destroyItem(ViewGroup view, int position, Object object) {
        view.removeView(view);
    }

    // 来判断显示的是否是同一张图片，这里我们将两个参数相比较返回即可
    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }

    @Override
    public int getCount() {
        return mImages.size();
    }

    @Override
    public Object instantiateItem(ViewGroup view, int position) {
        View imageLayout = LayoutInflater.from(mcontext).inflate(R.layout.item_bigpic,
                view, false);
        final ImageView imageView = (ImageView) imageLayout
                .findViewById(R.id.item_bigpic_image);
        final ImageView download = (ImageView) imageLayout.findViewById(R.id.item_bigpic_download);
        final PicItem image = mImages.get(position);
        ImageLoader.loadAds(mcontext, image.getUrl(), imageView);
        download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new getImageCacheAsyncTask(mcontext, download).execute(image.getUrl());
            }
        });
        view.addView(imageLayout);
        return imageLayout;
    }

    private class getImageCacheAsyncTask extends AsyncTask<String, Void, File> {
        private final Context context;
        View mparent;

        public getImageCacheAsyncTask(Context context, View parent) {
            this.mparent = parent;
            this.context = context;
        }

        @Override
        protected File doInBackground(String... params) {
            String imgUrl = params[0];
            try {
                return Glide.with(context)
                        .load(imgUrl)
                        .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                        .get();
            } catch (Exception ex) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(File result) {
            if (result == null) {
                return;
            }
            //此path就是对应文件的缓存路径
            String path = result.getPath();
            bmp = BitmapFactory.decodeFile(path);
            showPopupWindow(mparent);
        }
    }

    //保存操作
    private void showPopupWindow(View parent) {
        LayoutInflater inflater = LayoutInflater.from(mcontext);
        if (popWindow == null) {
            View view = inflater.inflate(R.layout.pop_download_pic,
                    null);
            popWindow = new PopupWindow(view, ViewPager.LayoutParams.MATCH_PARENT,
                    ViewPager.LayoutParams.MATCH_PARENT, true);
            initPop(view);
        }
        popWindow.setAnimationStyle(android.R.style.Animation_InputMethod);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        popWindow
                .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    public void initPop(View view) {
        TextView cancel = (TextView) view.findViewById(R.id.pop_cancel);
        TextView download = (TextView) view.findViewById(R.id.pop_download);
        download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                SavaImage(bmp, Environment.getExternalStorageDirectory()
                        .getPath() + "/hejiaoyu");
                popWindow.dismiss();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                popWindow.dismiss();
            }
        });
    }

    public void SavaImage(Bitmap bitmap, String path) {
        File file = new File(path);
        FileOutputStream fileOutputStream = null;
        if (!file.exists()) {
            file.mkdir();
        }
        try {
            fileOutputStream = new FileOutputStream(path + "/"
                    + System.currentTimeMillis() + ".png");
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            fileOutputStream.close();
            ToastShow.show(mcontext, "下载成功！");
        } catch (Exception e) {
            ToastShow.show(mcontext, "下载失败！");
            e.printStackTrace();
        }
    }
}

